<?php

class BaseController extends Zend_Controller_Action
{
    public $open_id;
    public $nickname;
    public $headimgurl;
    public $user_id;
    function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
    {
        // 微信授权后
        if (isset($_GET['state']) && $_GET['state'] == 'wxAuth' && isset($_GET['code'])) {
            $this->authBack();
        } else {
            if (\Util\Config::get('env','Environment') == 'dev') {
                $this->user_id = 1001;
                $this->open_id = 'dev-openid-xxxxxxxxx';
                $this->nickname = 'developer';
                $this->headimgurl = 'http://image.freshqiao.com/files/20170525103954921.jpg';
            } else {
                if($this->checkUserInfo() == false ) {
                    $this->setUserInfo();
                } else {
                    $this->getUserInfo();
                }
            }
        }
        parent::__construct($request, $response, $invokeArgs);
    }

    private function checkUserInfo(){
        return isset($_COOKIE['wx_user_info']);
    }

    private function getUserInfo()
    {
        $user_info = json_decode($_COOKIE['wx_user_info'],true);
        $this->user_id = $user_info['id'];
        $this->open_id = $user_info['open_id'];
        $this->nickname = $user_info['nickname'];
        $this->headimgurl = $user_info['headimgurl'];
    }

    private function setUserInfo()
    {
        $weixin_appid = \Util\Config::get('weixin_appid','Environment');
        $weixin_appsecret = \Util\Config::get('weixin_appsecret','Environment');
        $weixin_model = new Jsapipay();
        $config = array();
        $access_token = $weixin_model->gettoken($weixin_appid,$weixin_appsecret);
        $config['APPID'] = $weixin_appid;
        $config['APPSECRET'] = $weixin_appsecret;
        $open_id = $weixin_model->GetOpenid($config);
        $rest = new \Base\Rest();
        $req = array(
            'openid' => $open_id,
            'access_token' => $access_token,
        );
        $res = $rest->get('User',false,$req);
        if ($res->isSuccess()) {
            $weixin_info = $res->getResponse();
            $this->object2array($weixin_info);
            if ($weixin_info) {
                setcookie('wx_user_info',json_encode($weixin_info),time()+360000);
                $this->user_id = $weixin_info['id'];
                $this->open_id = $weixin_info['open_id'];
                $this->nickname = $weixin_info['nickname'];
                $this->headimgurl = $weixin_info['headimgurl'];
            }else{
                $this->lanchAuth();
            }
        }
    }

    private function lanchAuth()
    {
        $weixin_appid = \Util\Config::get('weixin_appid','Environment');
        $back_url = $this->getBackUrl();
        $get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$weixin_appid&redirect_uri=$back_url&response_type=code&scope=snsapi_userinfo&state=wxAuth#wechat_redirect";
        Header("Location: $get_code_url");
    }

    private function object2array(&$object) {
        $object =  json_decode( json_encode( $object),true);
        return  $object;
    }
    //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    public function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    private function getBackUrl()
    {
        $request_url = $_SERVER['REQUEST_URI'];
        $query_string = $_SERVER['QUERY_STRING'];
        $domain = \Util\Config::get('weixin_domain','Environment');
        $url = (strpos($domain,'http') == false) ? 'http://'.$domain : $domain;
        return $url.$request_url.'?'.$query_string;
    }

    private function authBack()
    {
        $code = $_GET['code'];
        $weixin_appid = \Util\Config::get('weixin_appid','Environment');
        $weixin_appsecret = \Util\Config::get('weixin_appsecret','Environment');
        $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$weixin_appid&secret=$weixin_appsecret&code=$code&grant_type=authorization_code";
        $token_url = $this->http_get($get_token_url);
        $token_url = json_decode($token_url,true);

        $refresh_token = $token_url["refresh_token"];
        $access_token = $token_url["access_token"];
        $open_id = $token_url["openid"];
        $info = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$open_id&lang=zh_CN";
        $user_info = $this->http_get($info);
        $user_info = json_decode($user_info,true);
        if ($user_info) {
            $article = new \Base\Rest();
            $post_data = array(
                'openid'=>$user_info['openid'],
                'nickname'=>$user_info['nickname'],
                'headimgurl'=>$user_info['headimgurl']
            );
            $req= array();
            $post = array('payload'=>base64_encode(http_build_query($post_data)));
            $rest_res = $article->post('User',$req,$post);
            if ($rest_res->isSuccess()) {
                $weixin_info = $rest_res->getResponse();
                $this->object2array($weixin_info);
                if ($weixin_info) {
                    setcookie('wx_user_info',json_encode($weixin_info),time()+360000);
                    $this->user_id = $weixin_info['id'];
                    $this->open_id = $weixin_info['open_id'];
                    $this->nickname = $weixin_info['nickname'];
                    $this->headimgurl = $weixin_info['headimgurl'];
                } else {
                    exit('服务器内部错误code[1]');
                }
            } else {
                exit('服务器内部错误code[2]');
            }
        }else{
            exit('服务器内部错误code[3]');
        }
    }
}